package sess

import (
	"net"
	"net/url"

	"gitee.com/night-tc/gobige/threads"
	"github.com/xtaci/kcp-go"
	"golang.org/x/net/websocket"
)

/*
网络连接的客户端
是去主动连接别人的
*/
// Dial 创建一个连接会话
func Dial(protocal ProtocalEnum, cb ISessCallBack, addr string, thgo *threads.ThreadGo) (INetSess, error) {
	var conn net.Conn
	var err error
	switch protocal {
	case Protocal_Tcp:
		if conn, err = net.Dial(protocal, addr); err != nil {
			return nil, err
		}
	case Protocal_Kcp:
		if conn, err = kcp.Dial(addr); err != nil {
			return nil, err
		}
	case Protocal_WebSocket:
		if conn, err = websocket.Dial(addr, "", convertWsToHttp(addr)); err != nil {
			return nil, err
		}
	default:
		return nil, Err_Unknown_ListenType.NewErr(nil, protocal)
	}

	sess := newNetSess(conn, cb, thgo, true, false)
	sess.SetVerify()

	return sess, nil
}

func convertWsToHttp(wsURL string) string {
	u, err := url.Parse(wsURL)
	if err != nil {
		panic(err)
	}

	u.Scheme = "http"
	u.Path = "/"
	u.RawQuery = ""
	u.Fragment = ""

	return u.String()
}
